package manager

import (
	"context"
	"go.uber.org/zap"
	apiAuth "navi-mumbai/app/api/admin/internal/auth"
	"navi-mumbai/app/api/admin/internal/model/pg"
	"navi-mumbai/common/auth"
	"navi-mumbai/common/ctxdata"
	"navi-mumbai/common/key/idkey"
	"navi-mumbai/common/xerr"

	"navi-mumbai/app/api/admin/internal/svc"
	"navi-mumbai/app/api/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateManagerLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateManagerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateManagerLogic {
	return &UpdateManagerLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateManagerLogic) UpdateManager(req *types.UpdateManagerReq) (resp *types.UpdateManagerResp, err error) {
	// verify permission level
	adminUid := ctxdata.GetUidFromCtx(l.ctx)
	level := ctxdata.GetAdminPermissionLevelFromCtx(l.ctx)
	if !l.svcCtx.Auth.VerifyPermissionLevel(l.ctx, apiAuth.SuperAdminUpdateManagerApi, adminUid, level) {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.AuthFail, "permission denied")
	}

	if req.Uid == idkey.SuperAdminUid && adminUid != idkey.SuperAdminUid {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.AuthFail, "permission denied")

	}

	// log
	defer func() {
		apiAuth.WriteAdminLog(l.ctx, l.svcCtx.ApiLogModel, adminUid, apiAuth.SuperAdminUpdateManagerApi, req, resp, err)
	}()

	var mg *pg.Manager
	mg, err = l.svcCtx.ManagerModel.FindOne(l.ctx, req.Uid)
	if err != nil && err != pg.ErrNotFound {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	if err == pg.ErrNotFound || mg == nil {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.UserNotExist, "uid not found")
	}

	if req.PermissionLevel != 0 && req.Uid != idkey.SuperAdminUid {
		mg.PermissionLevel = req.PermissionLevel
	}
	if req.AllowApi != "" && req.Uid != idkey.SuperAdminUid {
		mg.AllowApi = req.AllowApi
		// set admin api permission
		l.svcCtx.Auth.SetAdminApiPermission(mg.Uid, mg.AllowApi)
	}

	if req.Username != "" && req.Uid != idkey.SuperAdminUid {
		mg.Username = req.Username
	}
	if req.Password != "" {
		var hs []byte
		hs, err = auth.GenerateFromPassword(req.Password)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
		}

		mg.Userpass = string(hs)
	}

	err = l.svcCtx.ManagerModel.Update(l.ctx, mg)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	return
}
